package com.htfyun.ft.fragment.factory;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.htfyun.ft.R;
import com.htfyun.ft.utils.FileReadWrite;
import com.htfyun.hardware.HallStateController;

import androidx.annotation.Nullable;

public class FragmentHallSensor extends FactoryBaseFragment {

    private TextView txtValue;

    private Context mContext;

    private final static int MAX_TEST_COUNT = 3;

    private final static String HALL_REPORT_KEY_PATH = "/sys/class/htfyun-hall_observe/report_key_enabled";

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_factory_hall_sensor;
    }

    @Override
    protected void onInitView(@Nullable Bundle savedInstanceState) {
        super.onInitView(savedInstanceState);

        mContext = getContext();

        txtValue = (TextView) findViewById(R.id.txtValue);

        setBtnPassVisibility(View.GONE);

        txtValue.setText(getString(R.string.test_hall_state, HallStateController.getInstance().isHallOn() ? 1 : 0, 0));

    }


    @Override
    protected void onVisible() {
        super.onVisible();

        HallStateController.getInstance().registerHallStateChangedListener(onHallStateChangedListener);

        FileReadWrite.writeStringToFile(HALL_REPORT_KEY_PATH, "0");

    }

    @Override
    protected void onInvisible() {
        super.onInvisible();

        HallStateController.getInstance().unregisterHallStateChangedListener(onHallStateChangedListener);

        FileReadWrite.writeStringToFile(HALL_REPORT_KEY_PATH, "1");

    }

    private HallStateController.OnHallStateChangedListener onHallStateChangedListener =
            new HallStateController.OnHallStateChangedListener() {
                private int hallOnCount = 0;
                @Override
                public void onHallStateChangedListener(boolean isHallOn) {

                    if (isHallOn && (hallOnCount++) >= MAX_TEST_COUNT) {
                        delayAutoPass();
                    }

                    txtValue.setText(getString(R.string.test_hall_state, isHallOn ? 1 : 0, hallOnCount));

                }
            };

}
